App.controller('contractController', ['$rootScope', '$scope', '$state', 'Page', function ($rootScope, $scope, $state, Page) {


	$scope.getGridName = function(mediaId,type){
		if(type == 1) { //编辑
			return 'mediaGrid_' + mediaId;
		} else { //预览
			return 'mediaGridView_' + mediaId;
		}

	}

	Page.ajaxPostQuiet('customer/queryCustomer.do', null, function (resp) {
          $scope.customerList = resp.data;
    });

	$scope.mediaGrid = {
		options : {
			lazy : true
		},
		column_defs: [
			{
				target: 6,
				buttons: [
					{
						name: '删除',
						class: 'btn-delete',
						icon: 'fa-trash-o',
						event: function(row){
							Page.confirm("确定要取消该合同资源信息吗？", function () {
								Page.ajaxPost('contract/resource/delete/' + row.id + '.do', row, function (resp) {
									var gridName = $scope.getGridName(row.resourceInfo.mediaType,"1");
									$scope[gridName].query({contractId : row.contractId,mediaType : row.resourceInfo.mediaType});
								});
							});
						}
					}
				]
			}
		]
	},

	$scope.mediaGridView = {
		options : {
			lazy : true
		},
		column_defs: [
			{

			}
		]
	},

	$scope.busMediaTypes = [];
	$scope.stopMediaTypes = [];
	Page.ajaxPostQuiet('mediaType/all.do', null, function (resp) {
		$scope.mediaTypes = resp.data;
		for (var i = 0; i < $scope.mediaTypes.length; i++) {
			if($scope.mediaTypes[i].parentId == "1") {
				if($scope.mediaTypes[i].mediaName == "车身") {
					$scope.busBodyId = $scope.mediaTypes[i].mediaId;
				}
				//$($scope.busMediaTypes).each(function(index, media) {
				//	var gridName = "mediaGrid_" + media.mediaId;
				//	$scope[gridName] = angular.extend({}, $scope.mediaGrid);
				//	//$scope[gridName].gName = gridName;
				//});

				//$scope.busMediaTypes.push($scope.mediaTypes[i]);
			} else if($scope.mediaTypes[i].parentId == "2") {
				if($scope.mediaTypes[i].mediaName == "候车亭大板") {
					$scope.stopBodyId = $scope.mediaTypes[i].mediaId;
				}
			}
			var gridName = "mediaGrid_" + $scope.mediaTypes[i].mediaId;
			$scope[gridName] = angular.extend({}, $scope.mediaGrid);

			var viewGridName = "mediaGridView_" + $scope.mediaTypes[i].mediaId;
			$scope[viewGridName] = angular.extend({}, $scope.mediaGridView);
		}
	});
	
    $scope.contractGrid = {
        column_defs: [
            {
                target: 1,
                template: function(row) {
                    return '<a ed-click="showContractRes">'+row.contractNo+'</a>'
                }
            },
            {
                target: 8,
                buttons: [
                    {
                        name: '编辑',
                        clazz: 'btn-edit',
                        icon: 'fa-edit',
                        event: function(row){
							$scope.contract = row;
                    		$scope.contractAddModal.init(row).show();
							Page.ajaxPostQuiet('contract/mediaTypeCount.do', {parentId : '1',contractId : row.contractId}, function (resp) {
								$scope.typeCounts = resp.data;
							});
                        }
                    },
                    {
                        name: '删除',
                        clazz: 'btn btn-delete',
                        icon: 'fa-trash-o',
                        event: function(row){
                    		Page.confirm("确定要删除该合同信息吗？", function () {
				                Page.ajaxPost('contract/delete.do', row, function () {
				                    $scope.contractGrid.query();
				                });
				            });
                        }
                    }
                ]
            }
        ],
        add : function() {
            $scope.contractAddModal.init().show();
        },
        showContractRes : function(row) {
			$scope.viewContract = row;
            $scope.contractViewModal.init(row).show();
			Page.ajaxPostQuiet('contract/mediaTypeCount.do', {parentId : '1',contractId : row.contractId}, function (resp) {
				$scope.typeCounts = resp.data;
			});
        }
    };

    $scope.contractViewModal = {
    	init : function(contract){
    		this.contract = contract || {};
    		return this;
    	},
        //loadResource : function(){
    	//	this.datas = [];
    	//	$($scope.mediaTypes).each(function(index, media) {
    	//		if(!media.items){
         //           Page.ajaxPostQuiet('mediaType/' + media.mediaId + '/items.do', null, function (resp) {
			//			media.items = resp.data;
			//		});
         //       }
    	//		var data = angular.copy(media);
    	//		data.resources = [];
    	//		$scope.contractViewModal.datas.push(data);
         //   });
        //
    	//	if(this.contract.contractId){
         //   	Page.ajaxGetQuiet('contract/' + this.contract.contractId + '/resources.do',null, function (resp) {
         //           $(resp.data).each(function(index, resource) {
         //           	var mediaType = resource.resourceInfo.mediaType;
         //           	$($scope.contractViewModal.datas).each(function(index, data) {
         //           		 if(mediaType == data.mediaId){
         //           			 if(!data.resources){
         //           				 data.resources = [];
         //           			 }
         //           			 data.resources.push(resource);
         //           		 }
         //           	});
			//		});
         //       });
         //   }
    	//},
    	onShow : function() {
    		if(!this.contract){
    			this.contract = {};
    		}

			$scope.contractViewModal.viewSearchBus = true;
			$scope.contractViewModal.viewSearchStop = false;
			$($scope.customerList).each(function(index, customer) {
				if($scope.contractViewModal.contract.customerId == customer.customerId){
					$scope.contractViewModal.contract.customerName = customer.customerName;
				}
			});

			if(this.contract.contractId != undefined && this.contract.contractId != '') {
				var gridName = $scope.getGridName($scope.busBodyId,"2");
				$scope[gridName].query({contractId : this.contract.contractId,mediaType : $scope.busBodyId});
			}
        },
		clickBusTab : function() {
			$scope.contractViewModal.viewSearchBus = true;
			$scope.contractViewModal.viewSearchStop = false;
			Page.ajaxPostQuiet('contract/mediaTypeCount.do', {parentId : '1',contractId : this.contract.contractId}, function (resp) {
				$scope.typeCounts = resp.data;
			});
		},
		clickTab : function(mediaType) {
			var gridName = $scope.getGridName(mediaType,"2");
			$scope[gridName].query({contractId : this.contract.contractId,mediaType : mediaType});
		},
		clickStopTab : function() {
			//var gridName = $scope.getGridName($scope.stopBodyId,"2");
			//$scope[gridName].query({contractId : this.contract.contractId,mediaType : $scope.stopBodyId});
			$scope.contractViewModal.viewSearchBus = false;
			$scope.contractViewModal.viewSearchStop = true;
			Page.ajaxPostQuiet('contract/mediaTypeCount.do', {parentId : '2',contractId : this.contract.contractId}, function (resp) {
				$scope.typeCounts = resp.data;
				var gridName = $scope.getGridName($scope.stopBodyId,"2");
				$scope[gridName].query({contractId : $scope.viewContract.contractId,mediaType : $scope.stopBodyId});
			});
		}
    };

    //合同新增
    $scope.contractAddModal = {

    	init : function(contract){
    		this.contract = contract || {};
    		return this;
    	},
    	//loadResource : function(){
    	//	$(this.datas).each(function(index, data) {
    	//		data.resources = [];
         //   });
    	//
    	//	if(this.contract.contractId){
         //   	Page.ajaxGetQuiet('contract/' + this.contract.contractId + '/resources.do',null, function (resp) {
         //           $(resp.data).each(function(index, resource) {
         //           	var mediaType = resource.resourceInfo.mediaType;
         //           	$($scope.contractAddModal.datas).each(function(index, data) {
         //           		 if(mediaType == data.mediaId){
         //           			 if(!data.resources){
         //           				 data.resources = [];
         //           			 }
         //           			 data.resources.push(resource);
         //           		 }
         //           	});
			//		});
         //       });
         //   }
    	//},
        onShow : function() {
    		if(!this.contract){
    			this.contract = {};
    		}
            this.setTitle((this.contract.contractId ? '编辑' : '新增') + '合同');
            //this.datas = [];
            //$($scope.mediaTypes).each(function(index, media) {
    			//if(!media.items){
            //        Page.ajaxPostQuiet('mediaType/' + media.mediaId + '/items.do', null, function (resp) {
				//		media.items = resp.data;
				//	});
            //    }
    			//var data = angular.copy(media);
    			//data.resources = [];
    			//$scope.contractAddModal.datas.push(data);
            //});
            //
            //this.loadResource();

			$scope.contractAddModal.searchBus = true;
			$scope.contractAddModal.searchStop = false;
			if(this.contract.contractId != undefined && this.contract.contractId != '') {
				var gridName = $scope.getGridName($scope.busBodyId,"1");
				$scope[gridName].query({contractId : this.contract.contractId,mediaType : $scope.busBodyId});
			}

            this.importFile = {};
            this.watchFile = $scope.$watch('contractAddModal.importFile', function (newValue, oldValue, $scope) {
		        if (newValue == undefined || newValue.path == undefined || newValue.path == "") {
		            return;
		        }
		        var file = newValue;
		        var suffix = file.path.substring(file.path.lastIndexOf(".") + 1, file.path.length);
		        if (!(suffix == "xls" || suffix == "xlsx")) {
		            Page.notice("请选择excel文件!");
		            $scope.contractAddModal.importFile = {};
		            return;
		        }
		    });
        },
        onOkClick : function() {
            if(!$scope.validateForm.$valid) {
                $scope.validateForm.doValidate();
            } else {
            	this.contract.importFilePath = this.importFile.path || '';
                if(!this.contract.contractId) { //添加
                    Page.ajaxPost('contract/add.do', this.contract, function (resp) {
                    	Page.confirm("合同基本信息添加成功! 是否继续操作 ? ", function(){
                    		$scope.contractAddModal.setTitle('编辑合同');
                    		$scope.$apply(function () {
						     　　	$scope.contractAddModal.contract.contractId = resp.data.contractId;
						    });
                    		$scope.contractGrid.query();
                    	},function(){
                    		$scope.contractAddModal.watchFile();
                    		$scope.contractAddModal.hide();
                    		$scope.contractGrid.query();
                    	});
                    	
                    });
                } else {
                    Page.ajaxPost('contract/update.do', this.contract, function (resp) {
                       	Page.notice("合同信息保存成功!");
                        $scope.contractAddModal.watchFile();
                        $scope.contractAddModal.hide();
                        $scope.contractGrid.query();
                    });
                }
            }
        },
        onHidden : function() {
            $scope.validateForm.reset();
            this.watchFile();
			$scope.contract = {};
        },
        toImport : function(media){
        	$scope.contractImportModal.init(this.contract,media).show();
        },
        removeResource : function(row){
        	Page.confirm("确定要取消该合同资源信息吗？", function () {
				Page.ajaxPost('contract/resource/delete/' + row.id + '.do', row, function (resp) {
					  $scope.contractAddModal.loadResource();
				});
			});
        },
		clickBusTab : function() {
			$scope.contractAddModal.searchBus = true;
			$scope.contractAddModal.searchStop = false;
			Page.ajaxPostQuiet('contract/mediaTypeCount.do', {parentId : '1',contractId : this.contract.contractId}, function (resp) {
				$scope.typeCounts = resp.data;
			});
		},
		clickTab : function(mediaType) {
			var gridName = $scope.getGridName(mediaType,"1");
			$scope[gridName].query({contractId : this.contract.contractId,mediaType : mediaType});
		},
		clickStopTab : function() {
			$scope.contractAddModal.searchBus = false;
			$scope.contractAddModal.searchStop = true;
			Page.ajaxPostQuiet('contract/mediaTypeCount.do', {parentId : '2',contractId : this.contract.contractId}, function (resp) {
				$scope.typeCounts = resp.data;
				var gridName = $scope.getGridName($scope.stopBodyId,"1");
				$scope[gridName].query({contractId : $scope.contract.contractId,mediaType : $scope.stopBodyId});
			});
		}
    }
    
    $scope.contractImportModal = {
    	init : function(contract,media){
    		this.contract = contract || {};
    		this.media = media;
    		return this;
    	},
        onShow : function() {
    		this.importFile = {};
    		if(!this.contract){
    			this.contract = {};
    		}
            this.setTitle("合同资源明细导入-" + this.media.mediaName);
            this.importFile = {};
            this.watchFile = $scope.$watch('contractImportModal.importFile', function (newValue, oldValue, $scope) {
		        if (newValue == undefined || newValue.path == undefined || newValue.path == "") {
		            return;
		        }
		        var file = newValue;
		        var suffix = file.path.substring(file.path.lastIndexOf(".") + 1, file.path.length);
		        if (!(suffix == "xls" || suffix == "xlsx")) {
		            Page.alert("请选择excel文件!");
		            $scope.contractImportModal.importFile = {};
		            return;
		        }
		    });
        },
        onOkClick : function() {
            if(this.importFile.path != ''){
            	var param = {
            		contractId: this.contract.contractId,
            		importFilePath : this.importFile.path ,
            		mediaId : this.media.mediaId
            	};
            	Page.ajaxPost('contract/importResources.do', param , function (resp) {
            		Page.alert("数据导入成功!");
            		$scope.contractImportModal.hide();
            		$scope.contractAddModal.loadResource();
				},function(resp){
					var error  = "数据导入失败!";
					if(resp.data && (resp.data instanceof Array) && resp.data.length > 0){
						error += "<ol style='padding-left:10px;'>";
						for(var i = 0 ;i < resp.data.length; i++){
							if(i >= 3){
								error += '<li>... ...</li>';
								break;
							}
							error += '<li>'+ resp.data[i] + '</li>';
						}
						error += "</ol>";
					}else{
						error += "[" + resp.data + "]";
					}
					
					Page.alert(error);
				});
            	//$scope.contractImportModal.hide();
            }else{
            	Page.alert("请上传文件!");
            }
        },
        onHidden : function() {
            
        },
        downloadFile : function(){
        	Page.ajaxPost('contract/downloadModel.do', {mediaId:this.media.mediaId}, function () {
			});
        }
    }

}]);
